import { useSyncExternalStore } from "react"

export const useStorage = (key: string,initValue: any) => {

  // callback 是 React 内部提供的回调函数，用于通知组件重新渲染
  const subscribe = (callback: () => void) => {
    // 订阅浏览器api
    window.addEventListener("storage",callback)
    return () => {
      // 取消订阅
      window.removeEventListener("storage",callback)
    }
  }

  const getSnapshot = () => {
    return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) || '') : initValue
  }

  const res = useSyncExternalStore(subscribe, getSnapshot)

  const updateStorage = (value:any) => {
    localStorage.setItem(key,JSON.stringify(value))
    // 手动触发
    window.dispatchEvent(new StorageEvent("storage"))
  }

  return [res,updateStorage]
} 